package work02.atm;

public class ATMService {
    private IDBConnection dbconn;

    public ATMService(IDBConnection db) {
        this.dbconn = db;
    }

    public void withDraw(String cardNo, int amount) {
        //bug:should judge the account is or is not existing
        Account a = dbconn.getAccount(cardNo);
        //bug:the balance is not negative
        int balance = a.getBalance() - amount;
        a.setBalance(balance);
        dbconn.updateAccount(a);
    }

    public void deposit(String cardNo, int amount) {
        //bug:should judge the account is or is not existing
        Account a = dbconn.getAccount(cardNo);
        //should add the amount into the balance
        int balance = a.getBalance() - amount;
        a.setBalance(balance);
        dbconn.updateAccount(a);
    }

    public void transfer(String fromCardNo, String toCardNo, int amount) {
        //bug:should judge the account is or is not existing

        Account a = dbconn.getAccount(fromCardNo);
        //bug:should judge the account is or is not existing
        Account b = dbconn.getAccount(toCardNo);
        //bug:the balance is not negative
        int aBalance = a.getBalance() - amount;
        //bug:the balance may be overflow
        int bBalance = b.getBalance() + amount;
        a.setBalance(aBalance);
        b.setBalance(bBalance);
        //bug: should add the transaction
        //solution: should use the Jdbc transaction

        dbconn.updateAccount(a);
        dbconn.updateAccount(a);
    }

    public int inquiry(String cardNo) {
        //bug:should judge the account is or is not existing
        Account a = dbconn.getAccount(cardNo);
        return a.getBalance();
    }
}
